package com.flashmoment.video.service.impl;

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flashmoment.video.utils.PageUtils;
import com.flashmoment.video.utils.Query;

import com.flashmoment.video.dao.VideoDao;
import com.flashmoment.video.entity.VideoEntity;
import com.flashmoment.video.service.VideoService;


@Service("videoService")
public class VideoServiceImpl extends ServiceImpl<VideoDao, VideoEntity> implements VideoService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private VideoDao videoDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<VideoEntity> page = this.page(
                new Query<VideoEntity>().getPage(params),
                new QueryWrapper<VideoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<Map<String, Object>> findVideoData(int pageNumber, int pageSize, String keywords) {
        // 构建搜索请求
        SearchRequest searchRequest = new SearchRequest("video");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //2.2分页功能
        sourceBuilder.from(pageNumber);//当前页开始
        sourceBuilder.size(pageSize);//当前页展示数据条数
        // 构建查询条件
        MatchPhraseQueryBuilder matchPhraseQuery = QueryBuilders.matchPhraseQuery("videoTitle", keywords);
        sourceBuilder.query(matchPhraseQuery);

        // 构建高亮显示设置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("videoTitle");
        sourceBuilder.highlighter(highlightBuilder);

        // 设置超时时间
        sourceBuilder.timeout(TimeValue.timeValueSeconds(10));

        // 将搜索源构建器添加到搜索请求中
        searchRequest.source(sourceBuilder);
        ArrayList<Map<String, Object>> list = new ArrayList<>();

        try {
            // 执行搜索请求
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            // 解析搜索结果
            for (SearchHit hit : searchResponse.getHits().getHits()) {
                String id = hit.getId();
                String index = hit.getIndex();

                // 解析高亮字段
                HighlightField highlightField = hit.getHighlightFields().get("videoTitle");
                String highlightedVideoTitle = highlightField.fragments()[0].toString();

                Map<String, Object> sourceAsMap = hit.getSourceAsMap();


                if (StringUtils.isNotBlank(highlightedVideoTitle)){
                    //6.6将高亮字段取出来
                    Text[] fragments = highlightField.fragments();
                    //6.7定义一个新的名字
                    String newName="";
                    //6.8遍历找到对应高亮字段
                    for (Text fragment : fragments) {
                        //6.9拼接到一起
                        newName+=fragment;
                    }
                    //将原来的字段换成新的高亮字段
                    sourceAsMap.put("videoTitle",newName);
                    sourceAsMap.put("index",index);
                    sourceAsMap.put("id",id);
                }


                list.add(sourceAsMap);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回结果集
        return list;
    }

    @Override
    public List<VideoEntity> findVideoById(Integer id) {
        return videoDao.findVideoById(id) ;
    }

    @Override
    public List<VideoEntity> findMyLikesByUserId(Integer id) {
        return videoDao.findMyLikesByUserId(id);
    }

    @Override
    public List<VideoEntity> findMyCollectByUserId(Integer id) {
        return videoDao.findMyCollectByUserId(id);
    }

    @Override
    public List<VideoEntity> findMyShareByUserId(Integer id) {
        return videoDao.findMyShareByUserId(id);
    }

    @Override
    public List<String> SelectCollectAll(long id) { return videoDao.findSelectCollectByUserId(id);}

}